import React from 'react';
import { PlusOutlined, ExceptionOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ProFormTextArea,
  ProFormText,
  ProFormRadio,
  ProTable,
  ProColumns,
  ModalForm,
  ProFormGroup,
  ProFormMoney,
} from '@ant-design/pro-components';
import { Button, message, Tag } from 'antd';

import { convertTagColor, downloadFile, saveDataParams, proTableRequest } from '@/app/common/utils';

import { DictType } from '.';

interface DictDataItem {
  dictCode?: number;
  dictSort?: number;
  dictLabel?: string;
  dictValue?: string;
  status?: number;
  listClass?: string;
}

const columns: ProColumns<DictDataItem>[] = [
  {
    title: 'id',
    dataIndex: 'dictCode',
    key: 'dictCode',
    search: false,
    editable: false,
  },
  {
    title: '显示排序',
    dataIndex: 'dictSort',
    search: false,
    key: 'dictSort',
    valueType: 'digit',
  },
  {
    title: '数据标签',
    dataIndex: 'dictLabel',
    key: 'dictLabel',
    search: false,
    render: (_text, record) => {
      return [<Tag color={record.listClass}>{_text}</Tag>];
    },
  },
  {
    title: '数据键值',
    dataIndex: 'dictValue',
    search: false,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    valueType: 'select',
    valueEnum: {
      0: {
        text: '正常',
        status: 'Success',
      },
      1: {
        text: '停用',
        status: 'Error',
      },
    },
  },
  {
    title: '创建人',
    width: 90,
    dataIndex: 'createBy',
    valueType: 'text',
    key: 'createBy',
    editable: false,
    search: false,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    valueType: 'text',
    ellipsis: true,
    search: false,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    valueType: 'dateTime',
    hideInSearch: true,
    editable: false,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (_text, record, _, action) => {
      return [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.dictCode);
          }}
        >
          编辑
        </a>,
      ];
    },
  },
];

// 添加字典数据的表单
const AddDictData = (props: { dictType: string }) => {
  return (
    <ModalForm
      key="add-data"
      title={`添加字典数据 (${props.dictType})`}
      initialValues={{
        dictType: props.dictType,
        status: 0,
        listClass: 'default',
      }}
      onFinish={async (formData: any) => {
        const res = await $post('/system/dict/data', { data: formData });
        const isSuccess = res.code === 200;
        if (isSuccess) message.success('添加字典数据成功');
        return isSuccess;
      }}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          添加字典数据
        </Button>
      }
    >
      <ProFormText disabled name="dictType" label="字典类型" />
      <ProFormText required name="dictLabel" label="数据标签" />
      <ProFormText required name="dictValue" label="数据键值" />
      <ProFormGroup>
        <ProFormMoney
          required
          name="dictSort"
          fieldProps={{
            moneySymbol: false,
          }}
          label="显示排序"
          min={0}
          width="lg"
        ></ProFormMoney>
        <ProFormRadio.Group
          name="status"
          label="状态"
          radioType="button"
          options={[
            {
              label: '正常',
              value: 0,
            },
            {
              label: '停用',
              value: 1,
            },
          ]}
        />
      </ProFormGroup>
      <ProFormRadio.Group
        required
        name="listClass"
        label="标签回显样式"
        options={[
          {
            label: <Tag color={convertTagColor('default')}>默认</Tag>,
            value: 'default',
          },
          {
            label: <Tag color={convertTagColor('primary')}>主要</Tag>,
            value: 'primary',
          },
          {
            label: <Tag color={convertTagColor('success')}>成功</Tag>,
            value: 'success',
          },
          {
            label: <Tag color={convertTagColor('info')}>信息</Tag>,
            value: 'info',
          },
          {
            label: <Tag color={convertTagColor('warning')}>警告</Tag>,
            value: 'warning',
          },
          {
            label: <Tag color={convertTagColor('danger')}>危险</Tag>,
            value: 'danger',
          },
        ]}
      />
      <ProFormTextArea name="remark" label="备注" />
    </ModalForm>
  );
};

// 字典数据的表格
function EditDictData(props: { text: React.ReactNode; entity: DictType }) {
  const { dictType } = props.entity;

  return (
    <DrawerForm<DictType>
      key="dict-data"
      title={`字典数据 [ ${props.text} ]`}
      width="60%"
      trigger={<Button type="link">{props.text}</Button>}
      submitTimeout={2000}
      onFinish={async () => {
        return true;
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
      }}
    >
      <ProTable
        dateFormatter="string"
        columns={columns}
        rowKey="dictCode"
        request={proTableRequest('/system/dict/data/list', { dictType })}
        pagination={{
          showQuickJumper: true,
        }}
        editable={{
          type: 'single',
          onDelete: async key => {
            const res = await $delete(`/system/dict/data/${key}`);
            if (res.code === 200) {
              message.success('删除成功');
            } else {
              message.error(res.msg);
            }
          },
          onSave: async (_key, record) => {
            const res = await $put(`/system/dict/data`, { ...saveDataParams(record) });
            if (res.code === 200) {
              message.success('保存成功');
            } else {
              message.error(res.msg);
            }
          },
        }}
        toolBarRender={() => {
          return [
            <AddDictData dictType={dictType} />,
            <Button
              type="primary"
              icon={<ExceptionOutlined />}
              onClick={async () => {
                if (await downloadFile('/system/dict/data/export', { dictType })) {
                  message.success('下载成功');
                }
              }}
            >
              导出配置
            </Button>,
          ];
        }}
        search={false}
      />
    </DrawerForm>
  );
}

export default EditDictData;
